module TunecoreDirect
  
  # Represents a song in TuneCore.  Every song must belong to an #Album, which in turn must belong to
  # a #Person.  The actual media file (wav, mp3, flac, etc.) should be placed on Amazon S3, either using 
  # the TuneCore uploaders or a 3rd party library such as the 
  # Amazon_S3_Library_for_REST_in_Ruby[http://developer.amazonwebservices.com/connect/entry.jspa?externalID=135].
  class Song < TunecoreDirect::Base
    include TunecoreDirect
    
    attr_accessor :song_id, :album_id, :name, :artist_name, :s3_url, :track_num, :parental_advisory
    attr_accessor :errors, :s3_bucket_name, :s3_key, :asset_url
    
    def initialize(options = {})
      options.each do |k,v|
        self.send("#{k}=", v)
      end
    end
    
    # Returns that Album that this Song belongs to
    def album
      raise "Song#album is not supported in this version of the SDK"
    end
    
    # Returns the Person that this Song belongs to
    def person
      raise "Song#person is not supported in this version of the SDK"
    end
    
    # Save's the song in Tunecore's system
    def save
      req = Request.new
      params = {  "album_id"          => @album_id,
                  "name"              => @name,
                  "artist_name"       => @artist_name,
                  "track_num"         => @track_num,
                  "parental_advisory" => @parental_advisory,
                  "asset_url"         => @asset_url }
      
      res = req.create_song( params )
      raise "Unexpected return type: #{res.type}" unless res.type == "song"
      if res.status == "created"
        @song_id = res.object.song_id
        return true
      else
        @errors = res.errors
        return false
      end
    end 
    
    # Creates an Album object from a Rexml:Element
    def self.from_xml_element( song_element)
      song = self.new
      song.song_id            = song_element.elements["id"].text
      song.album_id           = song_element.elements["album-id"].text
      song.name               = song_element.elements["name"].text
      song.artist_name        = song_element.elements["artist-name"].text unless song_element.elements["artist-name"].nil?
      song.parental_advisory  = song_element.elements["parental-advisory"].text
      song.track_num          = song_element.elements["track-num"].text
      return song
    end  
    
    # Returns the URL for the upload tool
    def upload_url
      "#{tunecore_server}/partner/track_upload?api_key=#{api_key}&song_id=#{self.song_id}"
    end
    
  end
  
end